package com.levi.juc.lock;

import javax.lang.model.element.VariableElement;
import javax.swing.plaf.TableHeaderUI;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 可重入锁，获得外面的锁之后就相当于获得了里面的锁   为了防止死锁
 * lock锁必须配对使用，防止死锁
 */
public class ReentrantLockTest01 {
    public static void main(String[] args) {
        Phone phone = new Phone();
//        phone.sms();

        ExecutorService executorService = Executors.newSingleThreadExecutor();
        executorService.execute(()->{
            System.out.println(Thread.currentThread().getName());
            phone.sms();
        });
        executorService.shutdown();
    }
}

class Phone{
    Lock lock = new ReentrantLock();

    /**
     * 发短信方法  加锁
     * 在发短信方法中调用打电话方法
     */
    public void sms() {
        lock.lock();
        try {
            System.out.println("sms");
            call();//自动获得call()方法的锁
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    /**
     * 打电话方法  加锁
     */
    public void call() {
        lock.lock();
        try {
            System.out.println("call");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}
